using Microsoft.EntityFrameworkCore;
using AdminSystem.API.Models;

namespace AdminSystem.API.Data
{
    public class ApplicationDbContext : DbContext
    {
        public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options) : base(options)
        {
        }

        public DbSet<User> Users { get; set; }
        public DbSet<Role> Roles { get; set; }
        public DbSet<Permission> Permissions { get; set; }
        public DbSet<Module> Modules { get; set; }
        public DbSet<UserRole> UserRoles { get; set; }
        public DbSet<RolePermission> RolePermissions { get; set; }
        public DbSet<Content> Contents { get; set; }

        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            base.OnModelCreating(modelBuilder);

            // User configuration
            modelBuilder.Entity<User>(entity =>
            {
                entity.HasIndex(e => e.Username).IsUnique();
                entity.HasIndex(e => e.Email).IsUnique();
            });

            // Role configuration
            modelBuilder.Entity<Role>(entity =>
            {
                entity.HasIndex(e => e.Name).IsUnique();
            });

            // Permission configuration
            modelBuilder.Entity<Permission>(entity =>
            {
                entity.HasIndex(e => new { e.Resource, e.Action }).IsUnique();
            });

            // Module configuration
            modelBuilder.Entity<Module>(entity =>
            {
                entity.HasOne(e => e.Parent)
                    .WithMany(e => e.Children)
                    .HasForeignKey(e => e.ParentId)
                    .OnDelete(DeleteBehavior.Restrict);
            });

            // UserRole configuration
            modelBuilder.Entity<UserRole>(entity =>
            {
                entity.HasIndex(e => new { e.UserId, e.RoleId }).IsUnique();
                
                entity.HasOne(e => e.User)
                    .WithMany(e => e.UserRoles)
                    .HasForeignKey(e => e.UserId)
                    .OnDelete(DeleteBehavior.Cascade);

                entity.HasOne(e => e.Role)
                    .WithMany(e => e.UserRoles)
                    .HasForeignKey(e => e.RoleId)
                    .OnDelete(DeleteBehavior.Cascade);
            });

            // RolePermission configuration
            modelBuilder.Entity<RolePermission>(entity =>
            {
                entity.HasIndex(e => new { e.RoleId, e.PermissionId }).IsUnique();
                
                entity.HasOne(e => e.Role)
                    .WithMany(e => e.RolePermissions)
                    .HasForeignKey(e => e.RoleId)
                    .OnDelete(DeleteBehavior.Cascade);

                entity.HasOne(e => e.Permission)
                    .WithMany(e => e.RolePermissions)
                    .HasForeignKey(e => e.PermissionId)
                    .OnDelete(DeleteBehavior.Cascade);
            });

            // Content configuration
            modelBuilder.Entity<Content>(entity =>
            {
                entity.HasOne(e => e.Author)
                    .WithMany()
                    .HasForeignKey(e => e.AuthorId)
                    .OnDelete(DeleteBehavior.Restrict);
            });

            // Seed data
            SeedData(modelBuilder);
        }

        private void SeedData(ModelBuilder modelBuilder)
        {
            // Seed default roles
            modelBuilder.Entity<Role>().HasData(
                new Role { Id = 1, Name = "SuperAdmin", Description = "Super Administrator with full access" },
                new Role { Id = 2, Name = "Admin", Description = "Administrator with limited access" },
                new Role { Id = 3, Name = "User", Description = "Regular user with basic access" }
            );

            // Seed default permissions
            var permissions = new List<Permission>
            {
                new Permission { Id = 1, Name = "user.create", Description = "Create users", Resource = "User", Action = "Create" },
                new Permission { Id = 2, Name = "user.read", Description = "Read users", Resource = "User", Action = "Read" },
                new Permission { Id = 3, Name = "user.update", Description = "Update users", Resource = "User", Action = "Update" },
                new Permission { Id = 4, Name = "user.delete", Description = "Delete users", Resource = "User", Action = "Delete" },
                new Permission { Id = 5, Name = "role.create", Description = "Create roles", Resource = "Role", Action = "Create" },
                new Permission { Id = 6, Name = "role.read", Description = "Read roles", Resource = "Role", Action = "Read" },
                new Permission { Id = 7, Name = "role.update", Description = "Update roles", Resource = "Role", Action = "Update" },
                new Permission { Id = 8, Name = "role.delete", Description = "Delete roles", Resource = "Role", Action = "Delete" },
                new Permission { Id = 9, Name = "module.create", Description = "Create modules", Resource = "Module", Action = "Create" },
                new Permission { Id = 10, Name = "module.read", Description = "Read modules", Resource = "Module", Action = "Read" },
                new Permission { Id = 11, Name = "module.update", Description = "Update modules", Resource = "Module", Action = "Update" },
                new Permission { Id = 12, Name = "module.delete", Description = "Delete modules", Resource = "Module", Action = "Delete" },
                new Permission { Id = 13, Name = "content.create", Description = "Create content", Resource = "Content", Action = "Create" },
                new Permission { Id = 14, Name = "content.read", Description = "Read content", Resource = "Content", Action = "Read" },
                new Permission { Id = 15, Name = "content.update", Description = "Update content", Resource = "Content", Action = "Update" },
                new Permission { Id = 16, Name = "content.delete", Description = "Delete content", Resource = "Content", Action = "Delete" }
            };

            modelBuilder.Entity<Permission>().HasData(permissions);

            // Seed default modules
            modelBuilder.Entity<Module>().HasData(
                new Module { Id = 1, Name = "Dashboard", Description = "Main dashboard", Icon = "dashboard", Route = "/dashboard", SortOrder = 1 },
                new Module { Id = 2, Name = "User Management", Description = "User management module", Icon = "users", Route = "/users", SortOrder = 2 },
                new Module { Id = 3, Name = "Role Management", Description = "Role management module", Icon = "shield", Route = "/roles", SortOrder = 3 },
                new Module { Id = 4, Name = "Module Management", Description = "Module management", Icon = "grid", Route = "/modules", SortOrder = 4 },
                new Module { Id = 5, Name = "Content Management", Description = "Content management with rich text editor", Icon = "edit", Route = "/content", SortOrder = 5 }
            );

            // Seed SuperAdmin role permissions (all permissions)
            var superAdminPermissions = new List<RolePermission>();
            for (int i = 1; i <= 16; i++)
            {
                superAdminPermissions.Add(new RolePermission { Id = i, RoleId = 1, PermissionId = i });
            }
            modelBuilder.Entity<RolePermission>().HasData(superAdminPermissions);

            // Seed default admin user
            modelBuilder.Entity<User>().HasData(
                new User 
                { 
                    Id = 1, 
                    Username = "admin", 
                    Email = "admin@admin.com", 
                    PasswordHash = BCrypt.Net.BCrypt.HashPassword("admin123"), 
                    FullName = "System Administrator",
                    IsActive = true
                }
            );

            // Assign SuperAdmin role to default admin user
            modelBuilder.Entity<UserRole>().HasData(
                new UserRole { Id = 1, UserId = 1, RoleId = 1 }
            );
        }
    }
}
